import React from 'react';
import { User, Edit, Save, Globe, MapPin, Trash2, Settings, Shield, LogOut, AlertCircle, CheckCircle, Upload } from 'lucide-react';
import useProfileService from '../services/profile-service';
import { useState } from 'react';

const ProfilePage: React.FC = () => {
  const { user, updateProfile, isLoading, error, uploadAvatar, deleteAccount } = useProfileService();
  const [isEditing, setIsEditing] = useState(false);
  const [editedUser, setEditedUser] = useState(user || { name: '', email: '', avatar: '', bio: '', location: '', language: 'en', preferences: { notifications: true, theme: 'light', mapType: 'standard' } });
  const [activeTab, setActiveTab] = useState('profile');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showSuccessToast, setShowSuccessToast] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  const [showErrorToast, setShowErrorToast] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  // 监听用户数据变化，更新编辑状态
  React.useEffect(() => {
    if (user) {
      setEditedUser(user);
    }
  }, [user]);


  const handleDeleteAccount = () => {
    const success = deleteAccount();
    if (success) {
      setShowDeleteModal(false);
      setSuccessMessage('账户已删除');
      setShowSuccessToast(true);
      setTimeout(() => setShowSuccessToast(false), 3000);
      // 这里可以添加重定向逻辑
    } else {
      setErrorMessage('删除失败，请重试');
      setShowErrorToast(true);
      setTimeout(() => setShowErrorToast(false), 3000);
    }
  };

  // 处理头像上传
  const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      uploadAvatar(e.target.files[0])
        .then(() => {
          setSuccessMessage('头像上传成功');
          setShowSuccessToast(true);
          setTimeout(() => setShowSuccessToast(false), 3000);
        })
        .catch((err) => {
          setErrorMessage(err || '头像上传失败');
          setShowErrorToast(true);
          setTimeout(() => setShowErrorToast(false), 3000);
        });
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8 flex justify-between items-center">
          <h1 className="text-3xl font-bold text-gray-900">个人资料</h1>
          <button
            onClick={() => setIsEditing(!isEditing)}
            className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            {isEditing ? <Save size={18} className="mr-2" /> : <Edit size={18} className="mr-2" />}
            {isEditing ? '保存' : '编辑'}
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
          {/* 侧边栏 */}
          <div className="md:col-span-1">
            <div className="bg-white rounded-lg shadow overflow-hidden">
              <div className="p-6">
                <div className="flex flex-col items-center text-center">
                  <div className="relative">
                    <img
                      className="h-24 w-24 rounded-full object-cover border-4 border-white shadow-md"
                      src={editedUser.avatar || 'https://via.placeholder.com/150'} 
                      alt={editedUser.name}
                    />
                    {isEditing && (
                      <label className="absolute bottom-0 right-0 bg-blue-600 text-white rounded-full p-2 cursor-pointer hover:bg-blue-700 transition-colors duration-200">
                        <Upload size={16} />
                        <input type="file" accept="image/*" className="hidden" onChange={handleAvatarUpload} />
                      </label>
                    )}
                  </div>

                  <h2 className="text-xl font-semibold text-gray-900 mt-4">{editedUser.name}</h2>
                  <p className="text-gray-500 mt-1">{editedUser.email}</p>
                  <div className="mt-4 flex justify-center space-x-3">
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                      <Globe size={14} className="mr-1" /> {editedUser.language}
                    </span>
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                      <MapPin size={14} className="mr-1" /> {editedUser.location || '未知'}
                    </span>
                  </div>
                </div>
              </div>
              <div className="border-t border-gray-200">
                <nav className="px-4 py-2 space-y-1">
                  <button
                    onClick={() => setActiveTab('profile')}
                    className={`w-full px-3 py-2 text-left rounded-md text-sm font-medium ${activeTab === 'profile' ? 'bg-blue-50 text-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}`}
                  >
                    <User size={16} className="inline mr-2" /> 个人信息
                  </button>
                  <button
                    onClick={() => setActiveTab('settings')}
                    className={`w-full px-3 py-2 text-left rounded-md text-sm font-medium ${activeTab === 'settings' ? 'bg-blue-50 text-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}`}
                  >
                    <Settings size={16} className="inline mr-2" /> 设置
                  </button>
                  <button
                    onClick={() => setActiveTab('privacy')}
                    className={`w-full px-3 py-2 text-left rounded-md text-sm font-medium ${activeTab === 'privacy' ? 'bg-blue-50 text-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}`}
                  >
                    <Shield size={16} className="inline mr-2" /> 隐私
                  </button>
                  <button
                    onClick={() => setShowDeleteModal(true)}
                    className={`w-full px-3 py-2 text-left rounded-md text-sm font-medium text-red-600 hover:bg-red-50`}
                  >
                    <Trash2 size={16} className="inline mr-2" /> 删除账户
                  </button>
                  <button
                    className={`w-full px-3 py-2 text-left rounded-md text-sm font-medium text-gray-600 hover:bg-gray-50 hover:text-gray-900`}
                  >
                    <LogOut size={16} className="inline mr-2" /> 退出登录
                  </button>
                </nav>
              </div>
            </div>
          </div>

          {/* 主内容 */}
          <div className="md:col-span-2">
            <div className="bg-white rounded-lg shadow overflow-hidden">
              {/* 加载状态 */}
              {isLoading && (
                <div className="p-6 flex justify-center items-center h-64">
                  <p className="text-gray-600">加载个人资料中...</p>
                </div>
              )}

              {/* 错误提示 */}
              {error && !isLoading && (
                <div className="p-6 bg-red-50 border border-red-200 rounded-lg m-4">
                  <div className="flex items-center">
                    <AlertCircle className="h-5 w-5 text-red-400 mr-2" />
                    <p className="text-red-700 text-sm">{error}</p>
                  </div>
                </div>
              )}

              {/* 内容区域 */}
              {!isLoading && !error && (
                <>
                  {activeTab === 'profile' && (
                    <div className="p-6">
                      <h3 className="text-lg font-medium text-gray-900 mb-4">个人信息</h3>
                      <div className="space-y-4">
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                            {isEditing ? (
                              <input
                                type="text"
                                value={editedUser.name}
                                onChange={(e) => setEditedUser({ ...editedUser, name: e.target.value })}
                                className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                              />
                            ) : (
                              <p className="mt-1 text-sm text-gray-900">{editedUser.name}</p>
                            )}
                          </div>
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            {isEditing ? (
                              <input
                                type="email"
                                value={editedUser.email}
                                onChange={(e) => setEditedUser({ ...editedUser, email: e.target.value })}
                                className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                              />
                            ) : (
                              <p className="mt-1 text-sm text-gray-900">{editedUser.email}</p>
                            )}
                          </div>
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">个人简介</label>
                          {isEditing ? (
                            <textarea
                              value={editedUser.bio || ''}
                              onChange={(e) => setEditedUser({ ...editedUser, bio: e.target.value })}
                              rows={3}
                              className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                            />
                          ) : (
                            <p className="mt-1 text-sm text-gray-900">{editedUser.bio || '未填写'}</p>
                          )}
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">位置</label>
                            {isEditing ? (
                              <input
                                type="text"
                                value={editedUser.location || ''}
                                onChange={(e) => setEditedUser({ ...editedUser, location: e.target.value })}
                                className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                              />
                            ) : (
                              <p className="mt-1 text-sm text-gray-900">{editedUser.location || '未填写'}</p>
                            )}
                          </div>
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">语言</label>
                            {isEditing ? (
                              <select
                                value={editedUser.language}
                                onChange={(e) => setEditedUser({ ...editedUser, language: e.target.value })}
                                className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                              >
                                <option value="en">英语</option>
                                <option value="zh">中文</option>
                                <option value="ja">日语</option>
                                <option value="ko">韩语</option>
                              </select>
                            ) : (
                              <p className="mt-1 text-sm text-gray-900">
                                {editedUser.language === 'en' ? '英语' :
                                  editedUser.language === 'zh' ? '中文' :
                                    editedUser.language === 'ja' ? '日语' :
                                      editedUser.language === 'ko' ? '韩语' :
                                        editedUser.language}
                              </p>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {activeTab === 'settings' && (
                    <div className="p-6">
                      <h3 className="text-lg font-medium text-gray-900 mb-4">设置</h3>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm font-medium text-gray-900">深色模式</p>
                            <p className="text-xs text-gray-500">启用或禁用深色模式</p>
                          </div>
                          <button
                            onClick={() => {
                              const newTheme = editedUser.preferences.theme === 'dark' ? 'light' : 'dark';
                              updateProfile({
                                preferences: { ...editedUser.preferences, theme: newTheme }
                              });
                            }}
                            className={`relative inline-flex items-center h-6 rounded-full w-11 transition-colors duration-200 ease-in-out ${editedUser.preferences.theme === 'dark' ? 'bg-blue-600' : 'bg-gray-200'}`}
                          >
                            <span className={`absolute left-0.5 bg-white border border-gray-300 h-5 w-5 rounded-full transition-transform duration-200 ease-in-out ${editedUser.preferences.theme === 'dark' ? 'transform translate-x-5' : 'transform translate-x-0'}`}></span>
                          </button>
                        </div>

                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm font-medium text-gray-900">通知</p>
                            <p className="text-xs text-gray-500">接收应用通知</p>
                          </div>
                          <button
                            onClick={() => updateProfile({ preferences: { ...editedUser.preferences, notifications: !editedUser.preferences.notifications } })}
                            className={`relative inline-flex items-center h-6 rounded-full w-11 transition-colors duration-200 ease-in-out ${editedUser.preferences.notifications ? 'bg-blue-600' : 'bg-gray-200'}`}
                          >
                            <span className={`absolute left-0.5 bg-white border border-gray-300 h-5 w-5 rounded-full transition-transform duration-200 ease-in-out ${editedUser.preferences.notifications ? 'transform translate-x-5' : 'transform translate-x-0'}`}></span>
                          </button>
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">默认语言</label>
                          <select
                            value={editedUser.language}
                            onChange={(e) => setEditedUser({ ...editedUser, language: e.target.value })}
                            className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md p-2"
                          >
                            <option value="en">英语</option>
                            <option value="zh">中文</option>
                            <option value="ja">日语</option>
                            <option value="ko">韩语</option>
                          </select>
                        </div>
                      </div>
                    </div>
                  )}

                  {activeTab === 'privacy' && (
                    <div className="p-6">
                      <h3 className="text-lg font-medium text-gray-900 mb-4">隐私设置</h3>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm font-medium text-gray-900">公开个人资料</p>
                            <p className="text-xs text-gray-500">允许其他用户查看您的个人资料</p>
                          </div>
                          <button
                            onClick={() => updateProfile({ preferences: { ...editedUser.preferences, publicProfile: !editedUser.preferences.publicProfile } })}
                            className={`relative inline-flex items-center h-6 rounded-full w-11 transition-colors duration-200 ease-in-out ${editedUser.preferences.publicProfile ? 'bg-blue-600' : 'bg-gray-200'}`}
                          >
                            <span className={`absolute left-0.5 bg-white border border-gray-300 h-5 w-5 rounded-full transition-transform duration-200 ease-in-out ${editedUser.preferences.publicProfile ? 'transform translate-x-5' : 'transform translate-x-0'}`}></span>
                          </button>
                        </div>

                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm font-medium text-gray-900">共享位置</p>
                            <p className="text-xs text-gray-500">允许应用访问您的位置信息</p>
                          </div>
                          <button
                            onClick={() => updateProfile({ preferences: { ...editedUser.preferences, shareLocation: !editedUser.preferences.shareLocation } })}
                            className={`relative inline-flex items-center h-6 rounded-full w-11 transition-colors duration-200 ease-in-out ${editedUser.preferences.shareLocation ? 'bg-blue-600' : 'bg-gray-200'}`}
                          >
                            <span className={`absolute left-0.5 bg-white border border-gray-300 h-5 w-5 rounded-full transition-transform duration-200 ease-in-out ${editedUser.preferences.shareLocation ? 'transform translate-x-5' : 'transform translate-x-0'}`}></span>
                          </button>
                        </div>
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>

        {/* 成功提示 */}
        {showSuccessToast && (
          <div className="fixed top-4 right-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded z-50">
            <div className="flex items-center">
              <CheckCircle className="h-5 w-5 mr-2" />
              <span>{successMessage}</span>
            </div>
          </div>
        )}

        {/* 错误提示 */}
        {showErrorToast && (
          <div className="fixed top-4 right-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded z-50">
            <div className="flex items-center">
              <AlertCircle className="h-5 w-5 mr-2" />
              <span>{errorMessage}</span>
            </div>
          </div>
        )}

        {/* 删除账户确认模态框 */}
        {showDeleteModal && (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4">确认删除账户</h3>
              <p className="text-sm text-gray-500 mb-6">此操作不可撤销。您确定要删除您的账户吗？</p>
              <div className="flex justify-end space-x-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  取消
                </button>
                <button
                  onClick={handleDeleteAccount}
                  className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                >
                  确认删除
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ProfilePage;